<template>
	<div class="branch-wrap">
		<div class="branch-box-wrap">
			<div class="branch-box">
				<el-button class="add-branch" type="success" plain round @click="addTerm">添加条件</el-button>
				<div class="col-box" v-for="(item, index) in nodeConfig.conditionNodes" :key="index">
					<div class="condition-node">
						<div class="condition-node-box">
							<div class="auto-judge" @click="show(index)">
								<div class="sort-left" v-if="index != nodeConfig.conditionNodes.length - 1" @click.stop="arrTransfer(index, -1)">
									<el-icon><el-icon-arrow-left /></el-icon>
								</div>
								<div class="title">
									<span class="node-title">{{ item.nodeName }}</span>
									<span class="priority-title">优先级{{ item.priorityLevel }}</span>
									<el-icon class="close" @click.stop="delTerm(index)"><el-icon-close /></el-icon>
								</div>
								<div class="content">
									<span>{{ toText(nodeConfig, index) }}</span>
								</div>
								<div class="sort-right" v-if="index != nodeConfig.conditionNodes.length - 1&&index != nodeConfig.conditionNodes.length - 2"
									@click.stop="arrTransfer(index)">
									<el-icon><el-icon-arrow-right /></el-icon>
								</div>
							</div>
							<div class="error_tip" style="transform: translate(550%, -60px);" v-if="item.error">
								<el-icon>
									<Warning />
								</el-icon>
							</div>
							<add-node v-model="item.childNode" :currentNode="item"></add-node>
						</div>
					</div>
					<slot v-if="item.childNode" :node="item"></slot>
					<div class="top-left-cover-line" v-if="index == 0"></div>
					<div class="bottom-left-cover-line" v-if="index == 0"></div>
					<div class="top-right-cover-line" v-if="index == nodeConfig.conditionNodes.length - 1"></div>
					<div class="bottom-right-cover-line" v-if="index == nodeConfig.conditionNodes.length - 1"></div>
				</div>
			</div>
			<add-node v-model="nodeConfig.childNode" :currentNode="nodeConfig"></add-node>
		</div>
		<el-drawer title="条件设置" v-model="drawer" destroy-on-close append-to-body :size="1000" @close="save">
			<template #header>
				<div class="node-wrap-drawer__title">
					<label @click="editTitle" v-if="!isEditTitle">{{ form.nodeName }}<el-icon
							class="node-wrap-drawer__title-edit"><el-icon-edit /></el-icon></label>
					<el-input v-if="isEditTitle" ref="nodeTitle" v-model="form.nodeName" clearable @blur="saveTitle"
						@keyup.enter="saveTitle"></el-input>
				</div>
			</template>
			<el-form label-width="140px" label-position="right">
				<div>
					<el-form-item label="条件组关系">
						<el-switch v-model="form.groupRelationMode" active-text="自定义关系" inactive-text="固定关系" />
					</el-form-item>
					<el-form-item v-if="form.groupRelationMode == false" label="固定关系">
						<el-switch v-model="form.groupMode" active-text="或" inactive-text="且" />
					</el-form-item>
					<el-form-item v-else label="自定义关系">
						<el-button type="danger" plain :icon="Delete" @click="delAlltag">清空选项</el-button>
						<el-card style="min-height: 200px;width: 100%;margin-top: 5px;">
							<el-tag v-for="(role, index) in form.groupRelation" :key="role.index" :type="role.type" closable
								@close="delTag(index)">{{ role.name }}</el-tag>
						</el-card>
						<div class="buttonList">
							<el-button v-for="(item, index) in buttonList" :key="index" :type="item.type"
								@click="addTag(item)">{{
									item.name }}</el-button>
						</div>
					</el-form-item>
				</div>
			</el-form>
			<div>
				<el-card v-for="(item, index) in form.conditionList" :key="index" shadow="never">
					<template #header>
						<div class="card-header">
							<span>{{ item.groupName }}</span>
							<el-switch v-model="item.mode" active-text="且" inactive-text="或" />
							<el-button v-if="form.conditionList.length > 1" @click="deleteGroup(index)"
								:icon="Delete"></el-button>
						</div>
					</template>
					<workFormTable v-model="item.conditionList" :addTemplate="addTemplate" :mode="item.mode"
						placeholder="暂无数据">
						<template #tableContent>
							<el-table-column prop="key" label="表单属性" width="200">
								<template #default="scope">
									<el-select v-model="scope.row.key" size="large" @change="keyChange(scope.row, $event)">
										<el-option v-for="item in keyOptions" :key="item.id" :label="item.name"
											:value="item.id" />
									</el-select>
								</template>
							</el-table-column>
							<el-table-column prop="expression" label="表达式" width="300">
								<template #default="scope">
									<el-input v-if="scope.row.keyType == 'expression'" v-model="scope.row.expression"
										type="textarea"></el-input>
									<el-select v-else v-model="scope.row.expression">
										<el-option v-for="item in expresOption[formIdObj[scope.row.key]?.type]"
											:key="item.key" :label="item.name" :value="item.key" />
									</el-select>
								</template>
							</el-table-column>
							<el-table-column prop="value" label="值" width="250">
								<template #default="scope">
									<condition v-model="scope.row" :formIdObj="formIdObj"></condition>
								</template>
							</el-table-column>
							<el-table-column label="表达式描述" prop="comments" width="200">
								<template #default="scope">
									<el-input v-if="scope.row.keyType == 'expression'"
										v-model="scope.row.comments"></el-input>
								</template>
							</el-table-column>
						</template>
					</workFormTable>
				</el-card>
			</div>
			<el-footer>
				<el-button type="primary" @click="addOneConditionGroup">添加条件组</el-button>
				<el-button type="success" @click="save">保存</el-button>
				<el-button @click="drawer = false">取消</el-button>
			</el-footer>
		</el-drawer>
	</div>
</template>

<script setup>
import { ref, computed, inject, watch, nextTick } from 'vue'
import addNode from './addNode.vue'
import condition from './components/condition.vue'
import { Warning, Delete } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'
import tool from '@/utils/tool'
import { toBranchText } from './utils/toText.js'
import workFormTable from './components/workFormTable.vue'
import { checkBranch } from './utils/check.js'
import config from './config/express.js'
const props = defineProps({
	modelValue: { type: Object, default: () => { } }
})
const emit = defineEmits(['update:modelValue'])
const nodeConfig = ref(JSON.parse(JSON.stringify(props.modelValue)))
watch(nodeConfig, (newValue) => {
	emit('update:modelValue', newValue)
}, {
	deep: true
})
const dataList = inject('dataList')
const isEditTitle = ref(false)
const form = ref({})
const buttonList = ref([
	{ name: '或', type: 'success', exp: '||' },
	{ name: '且', type: 'success', exp: '&&' },
	{ name: '(', type: 'danger', exp: '(' },
	{ name: ')', type: 'danger', exp: ')' }
])
const nodeTitle = ref(null)
const index = ref()
const drawer = ref(false)
const addTemplate = ref({
	key: '',
	keyType: '',
	mode: '',
	value: '',
	expression: '',
	comments: '',
	conditionSelectVal: [],
	deptList: [],
	employeeList: []
})
//下拉完整数据
const expresOption = ref(config.expression)
// //选择表单属性
const keyOptions = computed(() => {
	let deepCopy = JSON.parse(JSON.stringify(dataList.value.filter(res =>
		res.type != 'MultiSelect' &&
		res.type != 'Description' &&
		res.type != 'SelectMultiUser' &&
		res.type != 'SelectMultiDept' &&
		res.type != 'Layout' &&
		res.type != 'UploadImage' &&
		res.type != 'UploadFile'
	)))
	// deepCopy.push({
	// 	id: 'root',
	// 	name: '发起人',
	// 	type: "SelectUser",
	// 	typeName: "用户"
	// })

	return deepCopy;
})
//控制关系下拉数据
const formIdObj = computed(() => {
	var obj = {}
	for (var item of keyOptions.value) {
		obj[item.id] = item;
	}
	return obj
})
const formObj = computed(() => {
	var obj = {}
	for (var item of dataList.value) {
		obj[item.id] = item;
	}
	obj['root'] = {
		name: "发起人",
		type: 'SelectUser'
	}
	return obj
})
const keyChange = (row, val) => {
	let key = keyOptions.value.find(item => {
		return item.id == val
	})
	row.keyType = key.type
}
/**条件弹出框相关操作 */
const deleteGroup = (index) => {
	form.value.groupRelation = []
	buttonList.value = buttonList.value.slice(0, 4)
	form.value.conditionList.splice(index, 1)
	form.value.conditionList.map((item, index) => {
		let index1 = index + 1
		item.exp = 'c' + index1;
		item.groupName = '条件组' + index1;
		buttonList.value.push({ exp: item.exp, name: item.groupName, type: "primary" })
	});

}
//添加一个条件组
const addOneConditionGroup = () => {
	let index = form.value.conditionList.length + 1
	form.value.conditionList.push({
		mode: true,
		groupName: '条件组' + index,
		exp: 'c' + index,
		conditionList: [{
			key: '',
			keyType: '',
			mode: '',
			value: '',
			expression: '',
			conditionType: 'simple',
			comments: '',
			conditionSelectVal: [],
			deptList: [],
			employeeList: []
		}]
	})
	buttonList.value.push({ exp: 'c' + index, name: "条件组" + index, type: "primary" })
}
const addTag = (item) => {
	form.value.groupRelation.push(item)
}
const delTag = (index) => {
	form.value.groupRelation.splice(index, 1)
}
const delAlltag = () => {
	form.value.groupRelation = []
}
/**条件box相关操作 */
const show = (num) => {
	if (num + 1 == nodeConfig.value.conditionNodes.length) {
		return
	}
	index.value = num
	form.value = JSON.parse(JSON.stringify(nodeConfig.value.conditionNodes[num]))
	buttonList.value = buttonList.value.slice(0, 4)
	form.value.conditionList.forEach(item => {
		buttonList.value.push({ exp: item.exp, name: item.groupName, type: "primary" })
	})
	drawer.value = true
}
const editTitle = () => {
	isEditTitle.value = true
	nextTick(() => {
		nodeTitle.value.focus()
	})
}
const saveTitle = () => {
	isEditTitle.value = false
}
//删除某个条件分支要判断
const delTerm = (index) => {
	const node = JSON.parse(JSON.stringify(nodeConfig.value))
	node.conditionNodes.splice(index, 1)
	node.conditionNodes.map((item, index) => {
		item.priorityLevel = index + 1;
		item.nodeName = `条件${index + 1}`;
	});
	if (node.conditionNodes.length == 1) {
		if (node.childNode) {
			if (node.conditionNodes[0].childNode) {
				reData(node.conditionNodes[0].childNode, node.childNode)
			} else {
				node.conditionNodes[0].childNode = node.childNode
			}
			node.childNode.parentId = node.parentId
		}
		emit("update:modelValue", node.conditionNodes[0].childNode);
	}
	else {
		emit("update:modelValue", node);
	}
}
const reData = (data, addData) => {
	if (!data.childNode) {
		data.childNode = addData
	} else {
		reData(data.childNode, addData)
	}
}
const addTerm = () => {
	let len = nodeConfig.value.conditionNodes.length + 1;
	let param = {
		nodeName: "条件" + len,
		type: 3,
		parentId: nodeConfig.value.id,
		"groupMode": true,
		id: tool.random.getRandomId(),
		error: true,
		priorityLevel: len-1,
		conditionType: 'simple',
		groupRelationMode: false,
		groupRelation: [],
		conditionList: [{
			mode: true,
			groupName: '条件组1',
			exp: 'c1',
			conditionList: [{
				key: '',
				keyType: '',
				mode: '',
				value: '',
				expression: '',
				conditionSelectVal: [],
				deptList: [],
				employeeList: []
			}]
		}],
		nodeUserList: [],
		childNode: null,
	}
	nodeConfig.value.conditionNodes.splice(-1,0,param);
	nodeConfig.value.conditionNodes[len-1].priorityLevel = len
	emit("update:modelValue", nodeConfig.value)
}
const arrTransfer = (index, type = 1) => {
	nodeConfig.value.conditionNodes[index] = nodeConfig.value.conditionNodes.splice(index + type, 1, nodeConfig.value.conditionNodes[index])[0]
	nodeConfig.value.conditionNodes.map((item, index) => {
		item.priorityLevel = index + 1
	})
	emit("update:modelValue", nodeConfig.value)
}
const toText = (node, index) => {
	if (node.conditionNodes[index].conditionType == 'express') {
		return node.conditionNodes[index].conditionList[0].comments
	}
	return toBranchText(node, index, formObj)
}

const save = () => {
	let node = JSON.parse(JSON.stringify(nodeConfig.value))
	node.conditionNodes[index.value] = form.value
	checkBranch(node)
	nodeConfig.value.conditionNodes[index.value] = form.value
	nodeConfig.value.conditionNodes.forEach((item, num) => {
		item.placeHolder = toBranchText(nodeConfig.value, num, formObj)
	})
	emit('update:modelValue', nodeConfig.value)
	// if (checkBranch(node) !== false) {
	// 	nodeConfig.value.conditionNodes[index.value] = form.value
	// 	nodeConfig.value.conditionNodes.forEach((item, num) => {
	// 		item.placeHolder = toBranchText(nodeConfig.value, num, formObj)
	// 	})
	// 	emit('update:modelValue', nodeConfig.value)
	// }
}
</script>

<style lang="less" scoped>
.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.buttonList {
	width: 100%;
	height: auto;
	margin: 10px;
}
</style>
